const Koa = require("koa");
const KoaRouter = require("@koa/router");

const app = new Koa(); // 创建一个koa实例

const userRouter = new KoaRouter({ prefix: "/users" });

userRouter.get("/", (ctx, next) => {
  const isAuth = false;
  if (isAuth) {
    ctx.body = "用户列表";
  } else {
    // ctx.body = {
    //   code: -1003,
    //   message: '没有权限, 请先登录'
    // }

    ctx.app.emit("error", -1003, ctx);
  }
});

app.use(userRouter.routes());
app.use(userRouter.allowedMethods());

// 独立的文件: error-handler.js
app.on("error", (code, ctx) => {
  const errCode = code || 500;
  let message = "";
  switch (errCode) {
    case -1001:
      message = "用户名不存在";
      break;
    case -1002:
      message = "密码错误";
      break;
    case -1003:
      message = "没有权限, 请先登录";
      break;
  }

  const body = {
    code: errCode,
    message,
  };

  ctx.body = body;
});

app.listen(6000, () => {
  console.log("服务器启动成功");
});
